package com.voxel.sense.infomsg.module.firm.details.average;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.com.common.utils.L;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.constants.TimeConstants;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.TabEntity;
import com.voxel.sense.infomsg.module.common.VRecyclerFrag;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.ClockInsDetailsEntity;

/**
 *
 */
public class DataAverageFrag extends VRecyclerFrag<DataAverageContract.Presenter, ClockInsDetailsEntity>
        implements DataAverageContract.View<ClockInsDetailsEntity> {
    @BindView(R.id.ctl_tip)
    CommonTabLayout ctl_tip;
    @BindView(R.id.recycle_view)
    RecyclerView recycle_view;
    @BindView(R.id.tv_empty)
    TextView tv_empty;
    @BindView(R.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.empty_view)
    EmptyView empty_view;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.appbar_layout)
    AppBarLayout appbar_layout;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private RecyclerAdapter mAdapter;
    private String mSId;
    private TimePickerView pvTime;//时间选择器
    private String[] mTitles = {"有效日", "日", "月", "年"};
    private String[][] mRecordTime = new String[4][2];
    private int mCurrentType = DataAverageContract.VALID_DAY_AVG;
    private String mDeteFormat = Constants.TimeYMDFormat;

    @Override
    protected int getContentLayoutId() {
        return R.layout.frag_data_average;
    }

    @Override
    protected DataAverageContract.Presenter initPresenter() {
        return new DataAveragePresenter(this);
    }

    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        if (bundle == null)
            return;
        mSId = bundle.getString(IntentConstants.STRING_TYPE);
    }

    @Override
    protected void onFirstInit() {
        super.onFirstInit();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }
        ctl_tip.setTabData(mTabEntities);
    }

    @Override
    protected void initData() {
        super.initData();
        //初始化recycle
        empty_view.bind(refresh_layout);
        recycle_view.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new AverageRecycleAdapter();
        recycle_view.setAdapter(mAdapter);

        //默认加载日均值
        //初始化时间选择器
        initTimeSelectView(getDefDay(), true, true, true);

        //加载默认数据
        Calendar defDay = getDefDay();
        String nowString = TimeUtils.getNowString(new SimpleDateFormat(Constants.TimeYMDFormat));
        String start = TimeUtils.date2String(defDay.getTime(), new SimpleDateFormat(Constants.TimeYMDFormat));
        tv_start_time.setText(start);
        tv_end_time.setText(nowString);
        refresh_layout.setEnableRefresh(false);
        String[] tm = {start, nowString};

        String nowDate = TimeUtils.getNowString(new SimpleDateFormat(Constants.TimeYMDFormat));
        String nowMothStart = TimeUtils.getNowMothOne();
        String nowMothEnd = TimeUtils.getNowMothEnd();
        String nowYearStart = TimeUtils.getNowYearOne();
        String nowYearEnd = TimeUtils.getNowYearEnd();
        String[] date = {nowDate, nowDate};
        String[] moth = {nowMothStart, nowMothEnd};
        String[] year = {nowYearStart, nowYearEnd};
        mRecordTime[0] = tm;
        mRecordTime[1] = date;
        mRecordTime[2] = moth;
        mRecordTime[3] = year;

        mPresenter.doRefresh(mSId, mCurrentType, start, nowString);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ctl_tip.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                String[] strings = mRecordTime[position];
                tv_start_time.setText(strings[0]);
                tv_end_time.setText(strings[1]);
                if (position == 0) {
                    mCurrentType = DataAverageContract.VALID_DAY_AVG;
                    //有效日均值
                    initTimeSelectView(getDefDay(), true, true, true);

                } else if (position == 1) {
                    //日均值
                    mCurrentType = DataAverageContract.DAY_AVG;
                    initTimeSelectView(getDefDay(), true, true, true);
                } else if (position == 2) {
                    //月均值
                    mCurrentType = DataAverageContract.MONTH_AVG;
                    initTimeSelectView(getDefMonth(), true, true, false);

                } else if (position == 3) {
                    //年均值
                    mCurrentType = DataAverageContract.YEAR_AVG;
                    initTimeSelectView(getYearStartTime(), true, false, false);
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadMore();
            }
        });
        empty_view.addRefreshBtnEvent(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreData();
            }
        });
        //由于进入界面就会加载数据，这时无效显示刷新按钮
        empty_view.setRefreshBtnVisible(false);
    }


    @Override
    public RecyclerAdapter<ClockInsDetailsEntity> getRecyclerViewAdapter() {
        return mAdapter;
    }


    @OnClick({R.id.btn_search, R.id.tv_start_time, R.id.tv_end_time})
    void onClickEvnet(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                pvTime.show(tv_start_time);
                break;
            case R.id.tv_end_time:
                String starTime = tv_start_time.getText().toString();
                if (TextUtils.isEmpty(starTime)) {
                    super.showError("请先选择开始时间");
                    return;
                }
                //初始选择时间，是开始时间的下一个小时
                long millis = TimeUtils.string2Millis(starTime, new SimpleDateFormat(mDeteFormat));
                L.d("" + TimeUtils.millis2String(millis));
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(millis);
                pvTime.setDate(calendar);
                pvTime.show(tv_end_time);
                break;
            case R.id.btn_search:
                refreData();
                break;
        }
    }

    /**
     * 刷新数据
     */
    private void refreData() {
        String start = tv_start_time.getText().toString();
        String end = tv_end_time.getText().toString();
        String[] str = {start, end};
        int currentTab = ctl_tip.getCurrentTab();
        mRecordTime[currentTab] = str;
        mPresenter.doRefresh(mSId, mCurrentType, start, end);
    }

    @Override
    public void showLoading(String str) {
        empty_view.triggerLoading();
    }


    @Override
    public void onRefreshFinish() {
        super.onRefreshFinish();
        empty_view.setRefreshBtnVisible(true);
    }

    /**
     * 初始化时间选择器
     */
    private void initTimeSelectView(Calendar defData, boolean year, boolean month, boolean day) {
        //初始化时间选择器的开始及结束时间
//        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(Calendar.YEAR, 2018);
        startDate.set(Calendar.DATE, 1);
        startDate.set(Calendar.MONTH, 0);
        Calendar endDate = Calendar.getInstance();
        buildTimePicker(defData, startDate, endDate, year, month, day);
    }

    /**
     * 创建时间选择器
     *
     * @param defData 选择器的起始时间
     * @param endDate 选择器的终止时间
     */
    private void buildTimePicker(Calendar defData, Calendar stardDate, Calendar endDate, boolean year, boolean month, boolean day) {
        pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                onCoverTime(date, v);
            }
        })
                .setType(new boolean[]{year, month, day, false, false, false})//分别表示是否显示年，月，日，时，分，秒，默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setDate(defData)// 如果不设置的话，默认是系统时间*/
                .setRangDate(stardDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

    }


    private void onCoverTime(Date date, View v) {
//        转换时间格式
        mDeteFormat = Constants.TimeYMDFormat;
        if (mCurrentType == DataAverageContract.MONTH_AVG) {
            mDeteFormat = Constants.TimeYMFormat;
        } else if (mCurrentType == DataAverageContract.YEAR_AVG) {
            mDeteFormat = "yyyy";

        }

        String string = TimeUtils.date2String(date, new SimpleDateFormat(mDeteFormat));
        if (v.getId() == R.id.tv_start_time) {
            tv_start_time.setText(string);
            L.d("tv_start_time:" + TimeUtils.date2String(date));
        } else if (v.getId() == R.id.tv_end_time) {
            L.d("tv_end_time:" + TimeUtils.date2String(date));
            tv_end_time.setText(string);
        }
    }

    /**
     * 获取当前时间的前七天时间的开始最贱
     *
     * @return
     */
    private Calendar getDefDay() {
        Calendar instance = Calendar.getInstance();
        Date dateByNow = TimeUtils.getDateByNow(-7, TimeConstants.DAY);
        Date startOfDay = TimeUtils.getStartOfDay(dateByNow);
        instance.setTime(startOfDay);
        return instance;
    }

    /**
     * 获取当前月的开始时间
     *
     * @return
     */
    private Calendar getDefMonth() {
        Calendar instance = Calendar.getInstance();
        Date firstDayDateOfMonth = TimeUtils.getFirstDayDateOfMonth(TimeUtils.getNowDate());
        Date startOfDay = TimeUtils.getStartOfDay(firstDayDateOfMonth);
        L.d(TimeUtils.date2String(startOfDay));
        instance.setTime(startOfDay);
        instance.add(Calendar.MONTH, -1);
        return instance;
    }

    //获取年的开始时间
    private Calendar getYearStartTime() {
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.MONTH, 0);
        instance.set(Calendar.DATE, 1);
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        L.d(TimeUtils.date2String(instance.getTime()));
        return instance;
    }


}
